﻿using System;
using System.Threading.Tasks;
using Icinetic.FeedCategorySample.Common.Base;
using Icinetic.FeedCategorySample.ViewModel;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;

namespace Icinetic.FeedCategorySample
{
    public sealed partial class MainPage : LayoutAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();
            DataContext = new MainPageViewModel();

            this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            await LoadData(e.Parameter);
            string visualState = DetermineVisualState(ApplicationView.Value);

            if (visualState != "Snapped")
            {
                if (Model.State == MainPageStateEnum.Cover)
                {
                    GoCover();
                }
            }
        }

        public MainPageViewModel Model
        {
            get { return DataContext as MainPageViewModel; }
        }

        private async Task LoadData(Object parameter)
        {
            MessageDialog message = null;
            try
            {
                await Model.LoadFeedList();
            }
            catch
            {
                message = new MessageDialog("No se han podido obtener las noticias. Inténtelo más tarde.", "Las noticias no están disponibles");
                message.Commands.Add(new UICommand("Aceptar"));
            }

            if (message != null)
                await message.ShowAsync();
        }

        private void MainButton_Click(object sender, RoutedEventArgs e)
        {
            appBarZoomIn.IsOpen = false;
            GoCover();
        }

        private void GoCover() 
        {
            this.Frame.Navigate(typeof(CoverPage), Model.CategoryList);
        }
    }
}
